package com.example.springbatch.schedule;

import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class ScheduleJob {

    private static final Logger log = LoggerFactory.getLogger(ScheduleJob.class);
    private Future<?> batchJobFuture;
    private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);

   // @Scheduled(cron = "0 17 * * * *")

    @PostConstruct
    public void runTask() {
        System.out.println("Running task - " + System.currentTimeMillis());

        if (batchJobFuture == null || batchJobFuture.isDone()) {
            batchJobFuture = executorService.submit(() -> {
                try {
                    int i = 0;
                    while (true) {
                        Thread.sleep(1000);
                        System.out.println(++i);
                    }
                } catch (Exception e) {
                    // 处理异常
                    log.error("Batch job failed");
                }
            });
            System.out.println("主线程执行");
            // 安排在六小时后取消任务
            executorService.schedule(() -> {
                System.out.println("batchJobFuture:"+batchJobFuture);
                System.out.println("isDone:"+batchJobFuture.isDone());
                if (batchJobFuture != null && !batchJobFuture.isDone()) {
                    System.out.println("进入批处理线程池");
                    batchJobFuture.cancel(true); // 强制停止任务
                    log.info("=======强制结束任务========");
                }
            }, 15, TimeUnit.SECONDS);
        }
    }
}
